﻿using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using Jib.Controls.DataGrid;
using MavlinkDebugger;
using MavlinkDebugger.PacketViewer;

namespace MavlinkPacketViewer
{
    public partial class MainPage
    {
        public MainPage()
        {
            InitializeComponent();
            DataContext = new MavlinkDebuggerVm();
        }

        private void ButtonClick(object sender, RoutedEventArgs e)
        {
            var dlg = new OpenFileDialog() { Filter = "Transmission Log Files (.tlog)|*.tlog" };
            var res = dlg.ShowDialog();
            if (res.HasValue && res.Value)
            {
                var str = dlg.File.OpenRead();
                (DataContext as MavlinkDebuggerVm).ProcessLogFile(str, rdoMavlinkFormat.IsChecked);
            }


        }

        private void MavlinkItemsDataGridLoadingRow(object sender, DataGridRowEventArgs e)
        {
            var obj = e.Row.DataContext as MavlinkItem;
            var c = Colors.Orange;
            c.A = 0x40;

            if (obj.ItemType == MavlinkItem.MavlinkItemType.FailedCRC)
                e.Row.Background = new SolidColorBrush(Color.FromArgb(0x80,0xFF,0,0));
            if (obj.ItemType == MavlinkItem.MavlinkItemType.UnusedBytes)
                e.Row.Background = new SolidColorBrush(c);  
        }

        private void MavlinkItemsDataGridUnloadingRow(object sender, DataGridRowEventArgs e)
        {
             var obj = e.Row.DataContext as MavlinkItem;

             if (obj.ItemType == MavlinkItem.MavlinkItemType.FailedCRC || obj.ItemType == MavlinkItem.MavlinkItemType.UnusedBytes)
             {
                 e.Row.ClearValue(BackgroundProperty);
             }
        }

        private void ViewSelectedBytes(object sender, RoutedEventArgs e)
        {
            var viewer = new BytesView {DataContext = mavlinkItemsDataGrid.SelectedItem};
            viewer.Show();
        }

        private void ViewPacket(object sender, RoutedEventArgs e)
        {
            var item = mavlinkItemsDataGrid.SelectedItem as MavlinkItem;
            var viewer = new PacketView { DataContext = item.MessageObject };
            viewer.Show();
        }


        private void MavlinkItemsDataGridSelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            var grid = sender as JibGrid;
            if (grid == null) return;

            if (grid.SelectedItems.Count != 1)
            {
                btnShowBytes.IsEnabled = false;
                return;
            }
            btnShowBytes.IsEnabled = true;

            var mavlinkItem = grid.SelectedItem as MavlinkItem;

            if (mavlinkItem == null)
                return;

            btnShowPacket.IsEnabled = (mavlinkItem.MessageObject != null);
        }
    }
}
